import { pageDictType, getDictTypeById, updateDictTypeStatus, deleteDictType } from '@/services/mainten/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns, ProDescriptionsItemProps } from '@ant-design/pro-components';
import {
  FooterToolbar,
  ModalForm,
  PageContainer,
  ProDescriptions,
  ProFormText,
  ProFormTextArea,
  ProTable,
  TableDropdown
} from '@ant-design/pro-components';
import { FormattedMessage, useIntl } from '@umijs/max';
import { Button, Drawer, Input, message, Modal } from 'antd';
import React, { useRef, useState, useEffect } from 'react';
import AddForm from './components/AddForm';
import { history } from 'umi';
import { DictTypeVo } from "../constants";
import dayjs from 'dayjs';
import { formatToLocalTime } from '@/utils/time';


const TableList: React.FC = () => {

   /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  const intl = useIntl();
  /**
   * @en-US Pop-up window of new window
   * @zh-CN 新建窗口的弹窗
   *  */
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);

  /**
   * @en-US The pop-up window of the distribution update window
   * @zh-CN 分布更新窗口的弹窗
   * */
  const [loading, setLoading] = useState(false);
  const [updateModalOpen, handleUpdateModalOpen] = useState<boolean>(false);
  // const [infoModalOpen, handleInfoModalOpen] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<DictTypeVo>();
  const [selectedRowsState, setSelectedRows] = useState<DictTypeVo[]>([]);
  const [editRow, setEditRow] = useState<DictTypeVo>();


  const getDictTypeInfo = async (id: string) => {
    try {
      const response = await getDictTypeById(id);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          throw new Error(response.msg);
        }
      }
      setEditRow(response.data);
    } catch (error) {
      message.error(intl.formatMessage({ id: "request.error.retry" }));
      return false;
    }
  };


  const queryPageData = async (pageParams: any) => {
    setLoading(true);
    try {
      const response = await pageDictType(pageParams);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
        }
      }
      return response.data;
    } catch (error) {
      console.error(error);
      message.error(intl.formatMessage({ id: "request.error.retry" }));
    }finally{
      setLoading(false);
    }
  };


  const pageQueryCustomer = async (params, sorter, filter) => {
    // 表单搜索项会从 params 传入，传递给后端接口。
    // console.log(params, sorter, filter);
    // const { current, pageSize, customerCode, customerName, customerStatus } = params
    // let queryParams = {};
    // if (current !== undefined) queryParams.current = current;
    // if (pageSize !== undefined) queryParams.pageSize = pageSize;
    // if (customerCode !== undefined) queryParams.likeCode = customerCode;
    // if (customerName !== undefined) queryParams.likeName = customerName;
    // if (customerStatus !== undefined) queryParams.status = Number(customerStatus);
    return await queryPageData(params);
  }

  const makeDelete = (record: DictTypeVo) => {
    Modal.confirm({
      title: intl.formatMessage({ id: 'pages.customer.address.delete.confirm.title' }),
      content: intl.formatMessage({ id: 'pages.customer.address.delete.confirm.content' }),
      okText: intl.formatMessage({ id: 'pages.button.confirm' }),
      cancelText: intl.formatMessage({ id: 'pages.button.cancel' }),
      onOk: async () => {
        const hide = message.loading(intl.formatMessage({ id: 'pages.common.processing' }));
        try {
          if (!record.id) {
            message.error(intl.formatMessage({ id: "request.error.create" }));
            return false;
          }
          const response = await deleteDictType(record.id);
          if (response.code != 0) {
            if (!response.msg) {
              throw new Error(intl.formatMessage({ id: "request.error.create" }));
            } else {
              message.error(response.msg);
              return false;
            }
          }
          hide();
          message.success(intl.formatMessage({ id: 'pages.customer.address.delete.success' }));
          if (actionRef.current) {
            actionRef.current.reload();
          }
        } catch (error) {
          console.error(error);
          hide();
          message.error(intl.formatMessage({ id: 'request.error.retry' }));
        }
      },
    });
  }


  const makeActive = async (record: DictTypeVo) => {
    const hide = message.loading('Processing...');
    try {
      // const status = record.customerStatus === 1 ? 0 : 1;
      if (!record.id) {
        message.error(intl.formatMessage({ id: "request.error.create" }));
        return false;
      }
      const response = await updateDictTypeStatus(record.id, record.status);
      if (response.code != 0) {
        if (!response.msg) {
          throw new Error(intl.formatMessage({ id: "request.error.create" }));
        } else {
          message.error(response.msg);
          return false;
        }
      }
      hide();
      if (actionRef.current) {
        actionRef.current.reload();
      }
    } catch (error) {
      console.error(error);      
      message.error(intl.formatMessage({ id: 'request.error.retry' }));
    }
  }

 

  const columns: ProColumns<DictTypeVo>[] = [
    {
      title: (
        <FormattedMessage
          id="pages.dict.name"
          defaultMessage="Dictionary Name"
        />
      ),
      dataIndex: "name",
      key: "name",
      width: 250,
    },
    {
      title: (
        <FormattedMessage
          id="pages.dict.type"
          defaultMessage="Dictionary Type"
        />
      ),
      dataIndex: "type",
      key: "type",
      width: 300,
    },
    {
      title: <FormattedMessage id="pages.status" defaultMessage="Status" />,
      dataIndex: "status",
      key: "status",
      width: 150,
      valueType: "select", // 下拉选择类型
      valueEnum: {
        1: {
          text: (
            <FormattedMessage
              id="pages.status.disabled"
              defaultMessage="Disabled"
            />
          ),
          status: "error",
        },
        0: {
          text: (
            <FormattedMessage
              id="pages.status.enabled"
              defaultMessage="Enabled"
            />
          ),
          status: "success",
        },
      },
    },
    {
      title: (
        <FormattedMessage id="pages.dict.remark" defaultMessage="Remark" />
      ),
      dataIndex: "remark",
      key: "remark",
      search: false, // 禁用搜索
    },
    {
      title: (
        <FormattedMessage id="pages.createTime" defaultMessage="createTime" />
      ),
      dataIndex: "createTime",
      key: "createTime",
      width: 180,
      sorter: true,
      valueType: "dateRange",
      hideInForm: true,
      search: {
        transform: (value) => ({
          startTime: value[0],
          endTime: value[1],
        }),
      },
      render: (_, record) => {
        return formatToLocalTime(record.createTime);
      },
    },
    {
      title: (
        <FormattedMessage id="pages.operating" defaultMessage="Operating" />
      ),
      dataIndex: "option",
      valueType: "option",
      fixed: "right",
      width: 180,
      disable: true,
      render: (_, record) => [
        <a
          key="edit"
          onClick={async () => {
            await getDictTypeById(record.id ? record.id : "");
            // console.log("current:"+JSON.stringify(record));
            setCurrentRow(record);
            handleUpdateModalOpen(true); // 打开编辑弹窗
          }}
        >
          <FormattedMessage id="pages.edit" defaultMessage="Edit" />
        </a>,
        <a
          key="info"
          onClick={() => {
            //打开字典value页面（可增、删、查、改）
            setCurrentRow(record);            
            history.push(`/mainten/dictionary/${record.type}`);
          }}
        >
          <FormattedMessage id="pages.dict.info" defaultMessage="Dict Info" />
        </a>,
        <TableDropdown
          key="actionGroup"
          onSelect={async(key) => {
            if (key === "delete") {
              // 手动触发重置密码逻辑
              makeDelete(record);
              setCurrentRow(record);
            } else if (key === "activte") {
              await makeActive(record);
              setCurrentRow(record);
            } else if (key === "reload") {
              actionRef.current?.reload();
            }
            // 可以根据需要扩展其他菜单项的逻辑
          }}
          menus={[
            {
              key: "activte",
              name: record.status == '1' ? (
                <FormattedMessage id="pages.status.enabled" defaultMessage="enabled" />
              ) : (
                <FormattedMessage id="pages.status.disabled" defaultMessage="disabled" />
              ),              
            },
            {
              key: "delete",
              name: (
                <FormattedMessage id="pages.delete" defaultMessage="Delete" />
              ),
              danger: true
            }, // 新增重置密码菜单项
          ]}
        />,
      ],
    },
  ];

  return (
    <PageContainer title={false}>
      <ProTable<DictTypeVo, API.PageParams>
        headerTitle={intl.formatMessage({
          id: 'pages.dict.list',
          defaultMessage: 'Dictionary List',
        })}
        actionRef={actionRef}
        loading={loading}
        rowKey="key"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            onClick={() => {
              //新建
              handleModalOpen(true);
            }}
          >
            <PlusOutlined /> {" "}
            <FormattedMessage id="pages.dict.create" defaultMessage="New" />
          </Button>,
        ]}
        request={pageQueryCustomer}
        columns={columns}
      // rowSelection={{
      //   onChange: (_, selectedRows) => {
      //     setSelectedRows(selectedRows);
      //   },
      // }}
      />


      <AddForm
        // width="40%"
        visible={createModalOpen}
        // onOpenChange={handleModalOpen}
        onCancel={async () => { handleModalOpen(false) }}
        onSuccess={function (): void {
          handleModalOpen(false)
          setCurrentRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>

      <AddForm
        visible={updateModalOpen}
        values={currentRow}
        onCancel={async () => {
          handleUpdateModalOpen(false);
          setCurrentRow(undefined);
          setEditRow(undefined);
        }}
        onSuccess={function (): void {
          handleUpdateModalOpen(false)
          setCurrentRow(undefined);
          setEditRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
        }}
      >
      </AddForm>
      {/* <ListForm
        visible={infoModalOpen}
        values={currentRow}
        onCancel={async () => {
          handleInfoModalOpen(false);
          setCurrentRow(undefined);
          setEditRow(undefined);
        }}
        onSuccess={function (): void {
          handleInfoModalOpen(false)
          setCurrentRow(undefined);
          setEditRow(undefined);
          // if (actionRef.current) {
          //   actionRef.current.reload();
          // }
        }}
      /> */}
    </PageContainer>
  );
};

export default TableList;
